package com.huawei.cloud.phone.management.common.validate;


import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class NotAllEmptyValidator implements ConstraintValidator<NotAllEmpty, Object> {
    private String[] names;

    @Override
    public void initialize(NotAllEmpty constraintAnnotation) {
        this.names = constraintAnnotation.names();
    }

    @Override
    public boolean isValid(Object data, ConstraintValidatorContext constraintValidatorContext) {
        try {
            for (String name : names) {
                Field field = data.getClass().getDeclaredField(name);
                field.setAccessible(true);
                Object fieldValue = field.get(data);
                if (Objects.isNull(fieldValue)) {
                    continue;
                }
                if (fieldValue instanceof Collection && !((Collection<?>)fieldValue).isEmpty()) {
                    return true;
                }
                if (fieldValue instanceof Map && !((Map<?, ?>)fieldValue).isEmpty()) {
                    return true;
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("get value failed", e);
        }
        return false;
    }
}
